class Tag < ActiveRecord::Base
  has_many :item_tags, :dependent => :destroy
  has_many :items, :through => :item_tags, :conditions => "items.status >= 0"
  
  validates_presence_of :name
  validates_uniqueness_of :name
  
  def to_s
    name
  end
  
#  def to_param
#    "#{id}-#{name}"
#  end
  
  # TODO 商品标签(tags)，存储格式：标签1(数量1),标签2(数量2), 暂时没有数量
  def tags
    #items.collect{ |item| item.tags.split(',') }.flatten.uniq rescue []
    items.collect{ |item| item.tags.split(',').map{|tag| tag =~ /\(\d+\)/ ? x : "#{tag}(1)" } }.flatten.uniq.reject{|tag| tag.sub(/\(\d+\)/, '') == self.name } rescue []
  end
  
  def cat1s
    items.collect{ |item| item.cat1 }.uniq
  end
  
  def cat2s(cat1_id)
    items.find_all_by_cat1_id(cat1_id).collect{ |item| item.cat2 }.compact.uniq
  end
end
